# 用户饮食记录管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime, date, timedelta

from myadmin.models import UserDietRecords, Users, Foods

# 用户饮食记录管理
def index(request, pIndex=1):
    """饮食记录列表页"""
    # 预加载关联数据，优化查询
    rlist = UserDietRecords.objects.select_related('user', 'food').all()
    mywhere = []
    
    # 排序处理
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            rlist = rlist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            pass
    
    # 搜索处理
    kw = request.GET.get("keyword", None)
    if kw:
        rlist = rlist.filter(
            Q(user__username__contains=kw) | 
            Q(food__food_name__contains=kw) |
            Q(meal_type__contains=kw)
        )
        mywhere.append(f'keyword={kw}')
    
    # 餐次筛选
    meal_type = request.GET.get('meal_type', '')
    if meal_type:
        rlist = rlist.filter(meal_type=meal_type)
        mywhere.append(f'meal_type={meal_type}')
    
    # 日期筛选
    start_date = request.GET.get('start_date', '')
    end_date = request.GET.get('end_date', '')
    if start_date:
        try:
            start = datetime.strptime(start_date, '%Y-%m-%d')
            rlist = rlist.filter(record_time__gte=start)
            mywhere.append(f'start_date={start_date}')
        except:
            pass
    if end_date:
        try:
            end = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
            rlist = rlist.filter(record_time__lt=end)
            mywhere.append(f'end_date={end_date}')
        except:
            pass
    
    # 用户筛选
    uid = request.GET.get('user', '')
    if uid:
        rlist = rlist.filter(user_id=uid)
        mywhere.append(f'user={uid}')
    
    # 食物筛选
    fid = request.GET.get('food', '')
    if fid:
        rlist = rlist.filter(food_id=fid)
        mywhere.append(f'food={fid}')
    
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(rlist, 4)  # 每页4条记录
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range
    
    # 获取相关数据用于筛选框
    users = Users.objects.all()
    foods = Foods.objects.all()
    meal_types = dict(UserDietRecords.MEAL_TYPE_CHOICES)  # 餐次类型字典
    
    context = {
        "recordlist": list2,
        'users': users,
        'foods': foods,
        'meal_types': meal_types,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'selected_meal': meal_type,
        'selected_uid': uid,
        'selected_fid': fid,
        'start_date': start_date,
        'end_date': end_date
    }
    return render(request, "myadmin/userdietrecords/index.html", context)

def add(request):
    """加载饮食记录添加表单"""
    users = Users.objects.all()
    foods = Foods.objects.all()
    meal_types = UserDietRecords.MEAL_TYPE_CHOICES
    context = {
        'users': users,
        'foods': foods,
        'meal_types': meal_types,
        'default_time': datetime.now().strftime('%Y-%m-%dT%H:%M')
    }
    return render(request, "myadmin/userdietrecords/add.html", context)

def insert(request):
    """执行饮食记录添加"""
    try:
        ob = UserDietRecords()
        # 基础信息
        ob.user_id = request.POST.get('user_id')
        ob.food_id = request.POST.get('food_id')
        
        # 数值验证
        quantity = request.POST.get('quantity')
        if not quantity or float(quantity) <= 0:
            raise ValueError("食物数量必须为正数")
        ob.quantity = quantity
        
        # 时间处理
        record_time = request.POST.get('record_time')
        if record_time:
            ob.record_time = datetime.strptime(record_time, '%Y-%m-%dT%H:%M')
        else:
            ob.record_time = datetime.now()
        
        # 餐次类型
        ob.meal_type = request.POST.get('meal_type')
        
        # 验证外键存在性
        if not Users.objects.filter(user_id=ob.user_id).exists():
            raise ValueError("关联用户不存在")
        if not Foods.objects.filter(food_id=ob.food_id).exists():
            raise ValueError("关联食物不存在")
        
        ob.save()
        context = {'info': "添加成功！"}
    except ValueError as e:
        context = {'info': f"添加失败：{str(e)}"}
    except Exception as err:
        print(err)
        context = {'info': "添加失败！"}
    return render(request, "myadmin/info.html", context)

def edit(request, rid=0):
    """加载饮食记录编辑表单"""
    try:
        # 严格检查rid是否为有效整数
        rid = int(rid)
        # 精确查询记录，只捕获记录不存在的异常
        ob = UserDietRecords.objects.get(record_id=rid)
        users = Users.objects.all()
        foods = Foods.objects.all()
        meal_types = UserDietRecords.MEAL_TYPE_CHOICES
        context = {
            'record': ob,
            'users': users,
            'foods': foods,
            'meal_types': meal_types,
            'record_time': ob.record_time.strftime('%Y-%m-%dT%H:%M')
        }
        return render(request, "myadmin/userdietrecords/edit.html", context)
    except UserDietRecords.DoesNotExist:
        # 仅当记录确实不存在时提示
        context = {'info': f"修改失败：ID为{rid}的记录不存在！"}
    except ValueError:
        # 处理rid不是整数的情况
        context = {'info': "错误：记录ID格式不正确！"}
    except Exception as err:
        # 其他未知错误显示具体原因
        print(f"编辑加载错误：{str(err)}")
        context = {'info': f"加载失败：{str(err)}"}
    return render(request, "myadmin/info.html", context)

def update(request, rid):
    """执行饮食记录编辑"""
    try:
        ob = UserDietRecords.objects.get(record_id=rid)
        
        # 基础信息更新
        ob.user_id = request.POST.get('user_id')
        ob.food_id = request.POST.get('food_id')
        
        # 数值验证
        quantity = request.POST.get('quantity')
        if not quantity or float(quantity) <= 0:
            raise ValueError("食物数量必须为正数")
        ob.quantity = quantity
        
        # 时间处理
        record_time = request.POST.get('record_time')
        if record_time:
            ob.record_time = datetime.strptime(record_time, '%Y-%m-%dT%H:%M')
        
        # 餐次类型
        ob.meal_type = request.POST.get('meal_type')
        
        # 验证外键存在性
        if not Users.objects.filter(user_id=ob.user_id).exists():
            raise ValueError("关联用户不存在")
        if not Foods.objects.filter(food_id=ob.food_id).exists():
            raise ValueError("关联食物不存在")
        
        ob.save()
        context = {'info': "修改成功！"}
    
    except UserDietRecords.DoesNotExist:
        context = {'info': "修改失败：记录不存在！"}
    except ValueError as e:
        context = {'info': f"修改失败：{str(e)}"}
    except Exception as e:
        print(f"修改错误详情：{str(e)}")
        context = {'info': f"修改失败：{str(e)}"}
    
    return render(request, "myadmin/info.html", context)

def delete(request, rid=0):
    """执行饮食记录删除"""
    try:
        ob = UserDietRecords.objects.get(record_id=rid)
        ob.delete()
        context = {'info': "删除成功！"}
    except UserDietRecords.DoesNotExist:
        context = {'info': "删除失败：记录不存在！"}
    except Exception as err:
        print(f"删除记录时出错: {err}")
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)